/**
 * 
 */
package org.rico.sport.filter;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 过滤器，检查是否已登录。未登录，跳转sso登录页面
 * @author rico
 */
public class LoginFilter implements Filter {
	private static final Logger logger = LoggerFactory.getLogger(LoginFilter.class);
	// 
	private Set<String> excludeUrls = new HashSet<>();

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	@Override
	public void init(FilterConfig config) throws ServletException {
		String excludeUrl = config.getInitParameter("excludeUrl");
		if(StringUtils.isNotBlank(excludeUrl)) {
			excludeUrls.addAll(Arrays.asList(excludeUrl.split(",")));
		}
	}

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse res = (HttpServletResponse)response;
		HttpSession session = req.getSession();
		
		String url = req.getRequestURL().toString();
		if(url.indexOf("loginCallback") != -1) {
			chain.doFilter(request, response);
			
		} else {
			boolean isLogin = false;
			if(session.getAttribute("isLogin") != null) {
				isLogin = (boolean) session.getAttribute("isLogin");
			}
			logger.info("System[news] login state[{}]", isLogin);
			
			if(!isLogin) {
				res.sendRedirect("http://localhost:8080/sso/login?systemId=sport&backUrl=http://localhost:8082/sport/loginCallback");
			} else {
				chain.doFilter(request, response);
			}
		}
	}

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#destroy()
	 */
	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

}
